<template>
	<div class="vip-list">
		<!-- 顶部菜单栏 -->
		<!-- <div class="tab">
      <el-tabs v-model="activeName">
        <el-tab-pane label="我的会员" name="myVip" @click="selected = []" />
        <el-tab-pane v-if="!$store.getters.banBtnList.includes('MCH_TAB_BATCH_OPERATION')" label="批量操作" name="modifyForm" />
        <el-tab-pane v-if="!$store.getters.banBtnList.includes('MCH_TAB_MEMBER_IMPORT')" label="导入会员" name="vipImport" />
        <el-tab-pane v-if="!$store.getters.banBtnList.includes('MCH_TAB_BATCH_OPERATION')" label="操作历史" name="accountHistory" />
        <el-tab-pane v-if="!$store.getters.banBtnList.includes('MCH_TAB_MEMBER_IMPORT')" label="导入历史" name="historyImport" />
      </el-tabs>
    </div> -->

		<!-- 我的会员 -->
		<div v-if="activeName === 'myVip'" class="vip-page">
			<div class="vip-content">
				<!-- <div class="left fl">
          <div class="category-tree-container">
            <el-scrollbar style="height:100%" class="hid-scrollbar-x">
              <el-form ref="filterForm" :model="filterForm" size="small">
                <el-form-item :class="{ pointerEvents: pointerEvents == 'memberGroup' }">
                  <div style="margin-left: 10px; font-weight: bold;">会员分群</div>
                  <el-button v-if="judgeOpen != 1" type="primary" style="margin: 10px;" @click="judgeOpenBtn">开通</el-button>
                  <el-button
                    v-for="(item, index) in memberGroup"
                    v-else
                    :key="index"
                    :type="item.checked ? 'primary' : ''"
                    round
                    :disabled="index == 3"
                    @click="memberGroupBtn(index)"
                  >
                    {{ item.groupName }}
                  </el-button>
                </el-form-item>
                <el-form-item :class="{ pointerEvents: pointerEvents == 'other' }">
                  <div style="margin-left: 10px; font-weight: bold;">持卡</div>
                  <el-button :type="filterForm.memberCategoryId.length === cardList.length ? 'primary' : ''" round @click="cardListSearch('all')">全部</el-button>
                  <el-button
                    v-for="v in cardList"
                    :key="v.id"
                    :type="filterForm.memberCategoryId.includes(v.id) ? 'primary' : ''"
                    round
                    @click="cardListSearch(v.id)"
                  >
                    {{ v.categoryName }}
                  </el-button>
                </el-form-item>
                <div v-for="(item, index) in labelGroup" :key="index">
                  <el-form-item :class="{ pointerEvents: pointerEvents == 'other' }">
                    <div style="margin-left: 10px">{{ item.tagGroup }}</div>
                    <el-button v-for="v in item.tags" :key="v.id" :type="filterForm.tagId.includes(v.id) ? 'primary' : ''" round @click="labelListSearch(v.id)">
                      {{ v.tagName }}
                    </el-button>
                  </el-form-item>
                </div>
              </el-form>
            </el-scrollbar>
          </div>
        </div> -->
				<!-- 右边 -->
				<div class="right">
					<div class="scrollbar-container">
						<el-scrollbar style="height:100%" class="hid-scrollbar-x">
							<el-form ref="filterForm" :rules="rules" :model="filterForm" label-width="80px" size="small"
								inline>
								<el-form-item label="用户名称" prop="customerName">
									<el-input v-model.trim="filterForm.customerName" placeholder="支持名称或昵称搜索" type="text"
										size="small" clearable style="max-width: 180px" />
								</el-form-item>
								<el-form-item label="手机号" prop="phone">
									<el-input v-model.trim="filterForm.phone" placeholder="注册手机号" type="text"
										size="small" clearable style="max-width: 180px" />
								</el-form-item>
								<!-- <el-form-item label="来源" prop="source">
                  <el-select v-model="filterForm.source" placeholder="请选择" collapse-tags clearable style="max-width: 180px">
                    <el-option v-for="item in source" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item> -->
								<el-form-item label="加入门店" prop="shopId">
									<el-select v-model="filterForm.pubDomainShopIds" filterable multiple collapse-tags
										clearable placeholder="可通过名称搜索" style="max-width: 180px"
										@change="val => idsChange(val, 'shop')">
										<el-option label="全部门店" value />
										<el-option v-for="(item, index) in manageShopList" :key="index"
											:label="item.name" :value="item.id" />
									</el-select>
								</el-form-item>
								<el-form-item label="加入时间" prop="registerTime" label-width="120px">
									<el-date-picker v-model="registerTime" type="datetimerange"
										range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
										format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00', '23:59:59']">
									</el-date-picker>
								</el-form-item>
								<!-- 筛选 -->
								<!--  <div class="app-main-filter-collapse-box">-->
								<el-collapse-transition>
									<div v-show="isShowMoreFilter">
										<!-- <el-form-item label="实体卡号" prop="entityCard">
                      <el-input v-model.trim="filterForm.entityCard" placeholder="实体卡号" type="text" size="small" clearable style="max-width: 180px" />
                    </el-form-item> -->
										<!-- <el-form-item label="微信卡号" prop="cardNo">
                      <el-input v-model.trim="filterForm.cardNo" placeholder="微信卡号" type="text" size="small" clearable style="max-width: 180px" />
                    </el-form-item> -->
										<!-- <el-form-item label="性别" prop="sex">
                      <el-select v-model="filterForm.sex" placeholder="请选择" collapse-tags clearable style="max-width: 180px">
                        <el-option v-for="item in sex" :key="item.value" :label="item.label" :value="item.value" />
                      </el-select>
                    </el-form-item> -->
										<br />
										<!-- <el-form-item label="已注册时长大于" prop="endTime" label-width="120px">
                      <el-input v-model.trim="filterForm.endYear" :disabled="endTime" style="width: 50px" maxlength="2" @change="dateChange" />
                      年
                      <el-input v-model.trim="filterForm.endMonth" :disabled="endTime" style="width: 50px" maxlength="2" @change="dateChange" />
                      月
                      <el-input v-model.trim="filterForm.endDay" :disabled="endTime" style="width: 50px" maxlength="2" @change="dateChange" />
                      日
                    </el-form-item> -->
										<!-- <el-form-item label="已注册时长小于" prop="startTime" label-width="120px">
                      <el-input v-model.trim="filterForm.startYear" :disabled="startTime" style="width: 50px" maxlength="2" @change="dateChange" />
                      年
                      <el-input v-model.trim="filterForm.startMonth" :disabled="startTime" style="width: 50px" maxlength="2" @change="dateChange" />
                      月
                      <el-input v-model.trim="filterForm.startDay" :disabled="startTime" style="width: 50px" maxlength="2" @change="dateChange" />
                      日
                    </el-form-item> -->
										<!-- <el-form-item label="最近消费日期" prop="recentConsumeTime" label-width="108px">
											<el-date-picker
												v-model="recentConsumeTime"
												type="daterange"
												range-separator="至"
												start-placeholder="开始日期"
												end-placeholder="结束日期"
											></el-date-picker>
										</el-form-item> -->
										<el-form-item label="加入时间" prop="registerTime" label-width="120px">
											<el-date-picker v-model="registerTime" type="datetimerange"
												range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
												format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00', '23:59:59']">
											</el-date-picker>
										</el-form-item>
									</div>
								</el-collapse-transition>

								<!-- 按钮组 -->
								<div>
									<el-form-item label=" " class="filter-btn">
										<el-button :loading="searchLoading" type="primary" round
											@click="submitFilterForm">查 询</el-button>
										<!-- <el-button type="text" round @click="isShowMoreFilter = !isShowMoreFilter">
											{{ isShowMoreFilter ? '隐藏' : '更多' }}筛选条件</el-button> -->
										<el-button type="text" round @click="resetFilterForm">重置筛选条件</el-button>
									</el-form-item>
								</div>
							</el-form>

							<!-- 表格内容 -->
							<div class="list-table hasCheckbox">
								<!-- 数据概览 -->
								<div class="flex-x-start flex-wrap" style="margin: 0 0 14px 40px">
									<!-- <div style="margin-bottom: 10px">
										<i class="el-icon-info" style="font-size: 20px;color: #999; margin-right: 10px; line-height: 20px" />
										<span style="line-height: 20px">
											查询会员数：
											<strong style="font-size: 24px; margin: 0 60px 0 20px;">{{ searchTotal }}</strong>
										</span>
									</div> -->
									<!-- <div style="margin-bottom: 10px">
										<i class="el-icon-info" style="font-size: 20px;color: #999; margin-right: 10px; line-height: 20px" />
										<span style="line-height: 20px">
											总会员数：
											<strong style="font-size: 24px; margin: 0 60px 0 20px;">{{ total }}</strong>
										</span>
									</div> -->
									<!-- <div style="margin-bottom: 10px">
										<i class="el-icon-info" style="font-size: 20px;color: #999; margin-right: 10px; line-height: 20px" />
										<span style="line-height: 20px">
											查询比例：
											<strong style="font-size: 24px; margin: 0 60px 0 20px;">{{ Math.round((searchTotal / total) * 100 * 100) / 100 || 0 }} %</strong>
										</span>
									</div> -->

									<div style="margin-bottom: 10px">
										<el-tooltip class="item" effect="dark" content="总用户数量，不被时间筛选影响"
											placement="top-start">
											<i class="el-icon-info"
												style="font-size: 20px;color: #999; margin-right: 10px; line-height: 20px" />
										</el-tooltip>
										<span style="line-height: 20px">
											累计用户数：
											<strong
												style="font-size: 24px; margin: 0 60px 0 20px;">{{ totalUserCount }}</strong>
										</span>
									</div>
									<div style="margin-bottom: 10px">
										<el-tooltip class="item" effect="dark" content="统计查询时间内微信授权登录的新增用户数量"
											placement="top-start">
											<i class="el-icon-info"
												style="font-size: 20px;color: #999; margin-right: 10px; line-height: 20px" />
										</el-tooltip>
										<span style="line-height: 20px">
											新增用户数：
											<strong
												style="font-size: 24px; margin: 0 60px 0 20px;">{{ addUserCount }}</strong>
										</span>
									</div>
									<!-- <div v-if="storedUserCountShow" style="margin-bottom: 10px">
										<el-tooltip class="item" effect="dark" content="统计查询时间内发生储值订单的人数，相同账号去重

" placement="top-start">
											<i class="el-icon-info"
												style="font-size: 20px;color: #999; margin-right: 10px; line-height: 20px" />
										</el-tooltip>
										<span style="line-height: 20px">
											储值用户数：
											<strong
												style="font-size: 24px; margin: 0 60px 0 20px;">{{ storedUserCount }}</strong>
										</span>
									</div> -->
								</div>

								<!-- 表格选择状态 -->
								<!--          <el-checkbox v-model="checkPage">全选本页</el-checkbox>-->
								<!--          <el-checkbox v-model="checkAll">全选所有页</el-checkbox>-->
								<!-- <el-button :disabled="selectSign" type="text" round @click="batchOption">批量操作</el-button> -->

								<!-- 表格内容 -->
								<el-table ref="memberTable" v-loading="tableLoading" :data="list" stripe
									style="width: 100%" size="small" element-loading-text="加载中" empty-text="暂无数据"
									@selection-change="handleClick($event)">
									<!-- <el-table-column type="selection" width="50" /> -->
									<el-table-column label="用户" width="300" fixed>
										<template slot-scope="scope">
											<div class="vip-member">
												<div class="vip-avatar"><img v-if="scope.row.headImg"
														:src="scope.row.headImg" alt /></div>
												<div>
													<div class="vip-name">
														{{ scope.row.customerName || '(空）' }}
														<svg-icon v-if="scope.row.sex === 1" icon-class="v-user-man"
															class="v-user-sex" />
														<svg-icon v-if="scope.row.sex === 0" icon-class="v-user-woman"
															class="v-user-sex" />
													</div>
													<div class="vip-detail">手机号：{{ scope.row.phone || '无' }}</div>
												</div>
											</div>
										</template>
									</el-table-column>
									<el-table-column label="资产" width="240">
										<template slot-scope="scope">
											<!-- <div class="vip-detail">持卡：{{ scope.row.categoryName }}</div> -->
											<span class="vip-detail">余额：{{ scope.row.totalBalance / 100 }} 元</span>
											<el-tooltip placement="bottom-start" effect="light">
												<div slot="content">
													实充：{{ scope.row.scBalance | parseNumberToThousands }} 元
													<br />
													赠送：{{ scope.row.giftBalance | parseNumberToThousands }} 元
												</div>
												<span style="color: #ffb72f; margin-left: 5px">明细</span>
											</el-tooltip>
											<!-- <div class="vip-detail">积分：{{ scope.row.points }} 个</div> -->
										</template>
									</el-table-column>
									<!-- <el-table-column label="标签">
										<template slot-scope="scope">
											<div v-if="!scope.row.tags">/</div>
											<div v-for="(item, index) of scope.row.tags" v-else :key="index" class="vip-detail">{{ item.tagName }}</div>
										</template>
									</el-table-column> -->
									<el-table-column label="加入">
										<template slot-scope="scope">
											<div>门店：{{ scope.row.shopName }}</div>
											<div>时间：{{ scope.row.registerTime }}</div>
										</template>
									</el-table-column>
									<el-table-column label="最近消费日期">
										<template slot-scope="scope">
											<div>{{ scope.row.recentConsumeTime ? scope.row.recentConsumeTime.substring(0,10) : '-' }}</div>
										</template>
									</el-table-column>
									<!-- <el-table-column label="注册" width="200">
										<template slot-scope="scope">
											<div class="vip-detail">来源：{{ scope.row.source ? scope.row.source : '无' }}</div>
											<div class="vip-detail">门店：{{ scope.row.shopName ? scope.row.shopName : '总部' }}</div>
											<div class="vip-detail">时间：{{ scope.row.createTime }}</div>
										</template>
									</el-table-column> -->
									<el-table-column v-if="!$store.getters.banBtnList.includes('BTN_MEMBER_DETAIL')"
										label="操作" width="60" fixed="right">
										<template slot-scope="scope">
											<el-button type="text" size="small"
												@click="goVipDetail(scope.$index, scope.row)">详情</el-button>
										</template>
									</el-table-column>
								</el-table>

								<!-- 分页 -->
								<pagination-direction v-if="paginationConfig.total !== 0" :config="paginationConfig"
									@sizeschange="sizesChange" @pagechange="pageChange" />
							</div>
						</el-scrollbar>
					</div>
				</div>
			</div>
		</div>

		<!-- 批量操作 -->
		<modify-form v-if="activeName === 'modifyForm'" ref="modifyForm" :select-option="selectOption"
			:select-group-id="selectGroupId" @changeTabName="changeTabName" />

		<!-- 会员导入 -->
		<vip-import v-if="activeName === 'vipImport'" @changeTabName="changeTabName" />

		<!-- 操作历史 -->
		<modify-record v-if="activeName === 'accountHistory'" />

		<!-- 导入历史 -->
		<import-record v-if="activeName === 'historyImport'" @changeTabName="changeTabName" />
	</div>
</template>

<script>
	import VipImport from './import/index';
	import ModifyRecord from './components/ModifyRecord';
	import ModifyForm from './components/ModifyForm';
	import ImportRecord from './import/components/ImportRecord';
	import {
		getVipList,
		getAllVipCardList,
		getTagsList,
		allMemberCount,
		selectMemberGroupConfigs,
		judgeOpenRfm
	} from '@/api/vip';
	import {
		userList,
		userCountInfo
	} from '@/api/UserCenter';
	import {
		validateMobilePhone
	} from '@/utils/validate';
	import {
		mapGetters
	} from 'vuex';

	export default {
		components: {
			VipImport,
			ModifyRecord,
			ModifyForm,
			ImportRecord
		},
		data() {
			/**
			 * 表单校验方法相关
			 */
			// 检验手机号
			const validatePhones = (rule, value, callback) => {
				if (value) {
					if (!validateMobilePhone(value)) {
						callback(new Error('手机号不正确'));
					} else {
						callback();
					}
				}
			};

			return {
				activeName: 'myVip', // 菜单栏
				tableLoading: false,
				searchLoading: false,
				isShowMoreFilter: false, // 折叠面板
				selectOption: null, // 批量跳转操作标签
				// 分页配置
				paginationConfig: {
					direction: 'center', // 分页位置
					layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
					pageSizes: [10, 20], // 分页pages
					total: 0,
					page: 1, // 页数-默认1
					pageSize: 10 // 每页条数-默认10
				},
				/**
				 * 表单
				 */
				filterForm: {
					startYear: '',
					startMonth: '',
					startDay: '',
					endYear: '',
					endMonth: '',
					endDay: '',
					tagId: [], // 标签
					memberCategoryId: [], // 会员卡类型
					memberGroupId: [], // 会员卡分群
					name: '', // 会员名称
					customerName: '', //用户名称
					phone: '',
					entityCard: '', // 实体卡号
					cardNo: '', // 微信卡号
					source: null,
					startTime: '',
					shopName: '', //加入的门店
					endTime: '',
					shopId: [], // 门店
					sex: '',
					pubDomainShopIds: [] //加入门店
				}, // 筛选条件
				list: [], // 会员列表
				total: null, // 会员总人数
				searchTotal: null, // 筛选人数
				totalUserCount: null, // 累计用户数
				addUserCount: null, // 新增用户数
				storedUserCount: null, // 储值用户数
				storedUserCountShow:true, //是否显示储值用户数
				startTime: false,
				endTime: false,
				registerTime: '', //加入时间
				recentConsumeTime: '', //最近消费日期
				rules: {
					phone: [{
						validator: validatePhones,
						trigger: ['change']
					}]
				},
				/**
				 * 下拉框选项内容
				 */
				source: [{
						value: 1,
						label: '线上开卡'
					},
					{
						value: 2,
						label: '门店推广'
					},
					{
						value: 3,
						label: '员工推广'
					},
					{
						value: 4,
						label: '会员分享'
					},
					{
						value: 5,
						label: '第三方平台'
					},
					{
						value: 6,
						label: '支付即会员'
					},
					{
						value: 7,
						label: '会员赠送'
					},
					{
						value: 8,
						label: '会员导入'
					}
				], // 来源条件
				sex: [{
						value: '1',
						label: '男'
					},
					{
						value: '0',
						label: '女'
					},
					{
						value: '-1',
						label: '未知'
					}
				], // 性别
				// 数据
				shopId: [], // 所有门店ids
				pubDomainShopIds: [], // 所有门店ids
				cardList: [], // 卡列表数据
				categoryId: [], // 所有卡ids
				lastShopIdArr: [], // 上一次选择
				labelGroup: [], // 标签组
				selectSign: true, // 批量处理的状态
				selected: {}, // 选中的会员

				// 会员分群
				memberGroup: [{
						name: '活跃会员',
						checked: false
					},
					{
						name: '预流失会员',
						checked: false
					},
					{
						name: '流失会员',
						checked: false
					},
					{
						name: '访问未入会会员',
						checked: false
					},
					{
						name: '未转化会员',
						checked: false
					},
					{
						name: '未复购会员',
						checked: false
					},
					{
						name: '加购未支付会员',
						checked: false
					},
					{
						name: '下单未支付会员',
						checked: false
					}
				],
				pointerEvents: null,
				judgeOpen: null, // 开通状态 0:未开通 1:已开通 2:开通失败 3:欠费停用 4:关闭 -1:机构未开通插件
				selectGroupId: ''
			};
		},
		computed: {
			...mapGetters(['manageShopList', 'banBtnList', 'fileBaseUrl'])
		},
		watch: {
			activeName(val) {
				if (val === 'myVip') {
					this.initData(1);
				}
			}
		},
		mounted() {
			if (this.$route.params.tagId) this.filterForm.tagId = [].concat(this.$route.params.tagId);
			this.isMounted = true;
			this.initData();
			this.fetchData();
			this.getTagList();
			if (this.$route.params.name) {
				this.activeName = this.$route.params.name;
				this.selectOption = 7;
			}
			// RFM
			this.judgeOpenRfmFun();

			// 从会员分群过来默认选中
			if (this.$route.params.groupId) {
				const groupId = this.$route.params.groupId;
				this.selectGroupId = groupId;
				this.activeName = 'modifyForm';

				// 选中分群
				// this.selectMemberGroupConfigsFun()
				// setTimeout(() => {
				//   this.memberGroup.forEach((el, index) => {
				//     if (el.id == groupId) {
				//       this.memberGroupBtn(index)
				//     }
				//   })
				// }, 500)
			}
		},
		methods: {
			/**
			 *  获取数据
			 */
			// 获取数据(卡类型)
			fetchData() {
				this.loading = true;
				getAllVipCardList()
					.then(res => {
						this.cardList = res.data;
						this.getIds();
					})
					.catch(() => {})
					.finally(() => {
						this.loading = false;
					});
			},
			// 获取所有Ids(卡id和门店id)
			getIds() {
				const shopId = [''];
				const categoryId = [''];
				this.manageShopList.forEach(v => {
					shopId.push(v.id);
				});
				this.cardList.forEach(v => {
					categoryId.push(v.id);
				});
				this.shopId = shopId;
				this.pubDomainShopIds = shopId
				this.categoryId = categoryId;
			},
			// 获取标签列表信息
			getTagList() {
				this.data = [];
				getTagsList().then(res => {
					res.data.forEach(e => {
						if (e.tags.length) {
							this.labelGroup.push(e);
						}
					});
				});
			},
			// 获取会员总数
			getAllMemberNum(params) {
				// allMemberCount().then(res => {
				// 	this.total = res.data.allCount;
				// });
				userCountInfo(params).then(res => {
					let {
						addUserCount,
						storedUserCount,
						totalUserCount
					} = res.data;
					this.totalUserCount = totalUserCount
					this.addUserCount = addUserCount
					this.storedUserCount = storedUserCount
				});
			},
			// 获取会员列表
			initData(page = this.paginationConfig.page, pageSize = this.paginationConfig.pageSize) {
				this.selectOption = null;
				// 加入page
				this.filterForm.page = page;
				this.filterForm.pageSize = pageSize;
				const params = Object.assign({}, this.filterForm);
				!params.memberCategoryId.length ? delete params.memberCategoryId : '';
				!params.tagId.length ? delete params.tagId : '';
				//是否显示储值用户数
				if(params.customerName || params.pubDomainShopIds.length > 0 || params.phone){
					this.storedUserCountShow = false
				}else{
					this.storedUserCountShow = true
				}
				// 如果不是更多搜索
				if (!this.isShowMoreFilter) {
					// 初始化数据
					delete params.entityCard;
					delete params.cardNo;
					delete params.startTime;
					delete params.endTime;
					delete params.sex;
					params.registerBeginDay = this.registerTime[0]
					params.registerEndDay = this.registerTime[1]
					params.consumeBeginDay = this.recentConsumeTime[0]
					params.consumeEndDay = this.recentConsumeTime[1]
				} else {
					// 日期处理
					// 判断正整数
					// const reg = /(^[1-9]\d*$)/
					if (this.startTime) {
						let year = params.endYear ? new Date(Date.now()).getFullYear() - params.endYear : new Date(Date
							.now()).getFullYear();
						let month = params.endMonth ? new Date(Date.now()).getMonth() + 1 - params.endMonth : new Date(Date
							.now()).getMonth() + 1;
						let day = params.endDay ? new Date(Date.now()).getDate() - params.endDay : new Date(Date.now())
							.getDate();
						if (day <= 0) {
							day += 28;
							month--;
						}
						if (month <= 0) {
							month += 12;
							year--;
						}
						params.endTime = year + '-' + month + '-' + day + ' 00:00:00';
						delete params.endYear;
						delete params.endMonth;
						delete params.endDay;
					}
					if (this.endTime) {
						let year = params.startYear ? new Date(Date.now()).getFullYear() - params.startYear : new Date(Date
							.now()).getFullYear();
						let month = params.startMonth ? new Date(Date.now()).getMonth() + 1 - params.startMonth : new Date(
							Date.now()).getMonth() + 1;
						let day = params.startDay ? new Date(Date.now()).getDate() - params.startDay : new Date(Date.now())
							.getDate();
						if (day <= 0) {
							day += 28;
							month--;
						}
						if (month <= 0) {
							month += 12;
							year--;
						}
						params.startTime = year + '-' + month + '-' + day + ' 00:00:00';
						delete params.startYear;
						delete params.startMonth;
						delete params.startDay;
					}
					!params.shopId.length ? delete params.shopId : '';
					!params.pubDomainShopIds.length ? delete params.pubDomainShopIds : '';
					params.registerBeginDay = this.registerTime[0]
					params.registerEndDay = this.registerTime[1]
					params.consumeBeginDay = this.recentConsumeTime[0]
					params.consumeEndDay = this.recentConsumeTime[1]
				}
				// 清除多余字段
				for (const key in params) {
					// eslint-disable-next-line
					if (params[key] === '' || params[key] === null || params[key] === undefined) {
						delete params[key];
					}
				}
				this.tableLoading = true;
				userList(params)
					.then(res => {
						if (res.data) {
							this.searchTotal = res.data.total;
							res.data.list.forEach((e, i) => {
								// 加一个索引
								e.index = i;
								// 来源处理
								// e.source = this.source[e.source - 1].label;
								// 注册时间处理
								const month = new Date(Date.now()).getMonth() - new Date(e.createTime)
									.getMonth();
								const year = new Date(Date.now()).getFullYear() - new Date(e.createTime)
									.getFullYear();
								const date = new Date(Date.now()).getDate() - new Date(e.createTime).getDate();
								if (year) {
									if (month > 0) {
										e.createTime = '已注册' + year + '年' + month + '月';
									} else if (month < 0) {
										e.createTime = year > 1 ? '已注册' + (year - 1) + '年' + (Number(month) +
											12) + '月' : '已注册' + (Number(month) + 12) + '月';
									} else {
										e.createTime = '已注册' + year + '年';
									}
								} else {
									if (month > 0) {
										if (date < 0) {
											e.createTime = month > 1 ? '已注册' + (month - 1) + '月' : '已注册近一个月';
										} else {
											e.createTime = '已注册' + month + '月';
										}
									} else {
										e.createTime = '已注册近一个月';
									}
								}
							});
							this.list = res.data.list;
							this.paginationConfig.total = res.data.total;
							this.paginationConfig.page = res.data.pageNum;
							// 选中的会员
							this.$nextTick(() => {
								if (this.selected[this.paginationConfig.page]) {
									this.selected[this.paginationConfig.page].forEach(e => {
										this.$refs.memberTable.toggleRowSelection(res.data.list[e
											.index], true);
									});
								}
							});
						} else {
							this.list = [];
							this.paginationConfig.total = 0;
							this.paginationConfig.page = 1;
						}
					})
					.finally(() => {
						this.tableLoading = false;
						this.searchLoading = false;
					});
				this.getAllMemberNum(params);
			},
			// 分页sizes改变
			sizesChange() {
				this.initData();
			},
			// 分页page改变
			pageChange() {
				this.initData();
			},

			// 查询会员分群及配置
			judgeOpenRfmFun() {
				judgeOpenRfm().then(res => {
					this.judgeOpen = res.data;
					if (this.judgeOpen == 1) {
						this.selectMemberGroupConfigsFun();
					}
				});
			},
			selectMemberGroupConfigsFun() {
				selectMemberGroupConfigs().then(res => {
					this.memberGroup = res.data;
					this.memberGroup.forEach(el => {
						el.checked = false;
					});
				});
			},
			judgeOpenBtn() {
				this.$router.push({
					name: 'PlugCenterList'
				});
			},

			/**
			 * 按钮组
			 */
			// 提交筛选表单
			submitFilterForm() {
				this.initData(1);
			},
			// 重置筛选表单
			resetFilterForm() {
				this.$refs.filterForm.resetFields();
				this.startTime = false;
				this.endTime = false;
				this.registerTime = '';
				this.recentConsumeTime = '';
				this.filterForm = {
					startYear: '',
					startMonth: '',
					startDay: '',
					endYear: '',
					endMonth: '',
					endDay: '',
					tagId: [], // 标签
					memberCategoryId: [], // 会员卡类型
					// memberGroupId: [], // 会员分群
					name: '', // 会员名称
					customerName: '', //用户名称
					phone: '',
					entityCard: '', // 实体卡号
					cardNo: '', // 微信卡号
					source: null,
					startTime: '',
					shopName: '', //加入的门店
					endTime: '',
					shopId: [], // 门店
					pubDomainShopIds:[],
					sex: ''
				};
				this.emptyMemberGroupFun();
				this.initData(1);
			},
			// 批量操作
			batchOption() {
				const selected = [];
				for (const key in this.selected) {
					this.selected[key].forEach(e => selected.push(e.phone));
				}
				setTimeout(() => {
					this.$refs.modifyForm.batchOption(selected);
				});
				this.activeName = 'modifyForm';
				this.selected = {};
				this.selectSign = true;
			},
			// 获取表格选中个数
			handleClick(e) {
				this.$nextTick(() => {
					this.selected[this.paginationConfig.page] = e;
					for (const key in this.selected) {
						if (this.selected[key].length) {
							this.selectSign = false;
							break;
						}
						this.selectSign = true;
					}
				});
			},

			/**
			 * 方法组
			 */
			// 日期输入框触发事件
			dateChange() {
				this.endTime = !!(this.filterForm.startYear || this.filterForm.startMonth || this.filterForm.startDay);
				this.startTime = !!(this.filterForm.endYear || this.filterForm.endMonth || this.filterForm.endDay);
			},
			// 按卡类型查询
			cardListSearch(index) {
				if (index !== 'all') {
					if (this.filterForm.memberCategoryId.includes(index)) {
						this.filterForm.memberCategoryId.splice(this.filterForm.memberCategoryId.indexOf(index), 1);
					} else {
						this.filterForm.memberCategoryId.push(index);
					}
				} else if (this.filterForm.memberCategoryId.length !== this.cardList.length) {
					this.filterForm.memberCategoryId = [];
					this.cardList.forEach(v => this.filterForm.memberCategoryId.push(v.id));
				} else {
					this.filterForm.memberCategoryId = [];
				}
				this.initData(1);
				this.memberGroupFun();
			},
			// 按标签查询
			labelListSearch(index) {
				if (this.filterForm.tagId.includes(index)) {
					this.filterForm.tagId.splice(this.filterForm.tagId.indexOf(index), 1);
				} else {
					this.filterForm.tagId.push(index);
				}
				this.initData(1);
				this.memberGroupFun();
			},

			// 控制会员分群点击
			memberGroupFun() {
				if (this.filterForm.memberCategoryId.length > 0 || this.filterForm.tagId.length > 0) {
					this.pointerEvents = 'memberGroup';
				} else {
					this.pointerEvents = '';
				}
			},

			// 跳转详情
			goVipDetail(index, row) {
				this.$router.push({
					name: 'detail',
					query: {
						customerId: row.customerId
					}
				});
			},
			// 页面跳转
			changeTabName(tabName) {
				this.activeName = tabName;
			},

			/**
			 * 状态组
			 */
			// 多选改变
			idsChange(val, type) {
				let lastIdsType = '';
				let idsType = '';
				switch (type) {
					case 'shop':
						lastIdsType = 'lastShopIdArr';
						idsType = 'pubDomainShopIds';
						break;
					case 'card':
						lastIdsType = 'lastCategoryIdArr';
						idsType = 'categoryId';
						break;
				}
				const lastVal = this[lastIdsType];
				if ((val.includes('') && (lastVal.length === 0 || !lastVal.includes(''))) || (!val.includes('') && !lastVal
						.includes('') && val.length === this[idsType].length - 1)) {
					this.filterForm[idsType] = this[idsType];
				} else if (!val.includes('') && lastVal.includes('')) {
					this.filterForm[idsType] = [];
				} else if (val.includes('') && val.length !== this[idsType].length) {
					const index = val.findIndex(v => v === '');
					if (index !== -1) val.splice(index, 1);
					this.filterForm[idsType] = val;
				}
				this[lastIdsType] = this.filterForm[idsType];
			},

			// 会员分群
			memberGroupBtn(index) {
				this.pointerEvents = null;
				this.memberGroup[index].checked = !this.memberGroup[index].checked;
				const memberGroupId = [];
				this.memberGroup.forEach(el => {
					if (el.checked) {
						this.pointerEvents = 'other';
						memberGroupId.push(el.id);
					}
				});
				this.filterForm.memberGroupId = memberGroupId;
				this.initData(1);
			},
			// 清空会员分群状态
			emptyMemberGroupFun() {
				this.memberGroup.forEach(el => {
					el.checked = false;
				});
				this.memberGroupId = [];
				this.pointerEvents = '';
			}
		}
	};
</script>
<style rel="stylesheet/scss" lang="scss">
	/* reset element*/
	.vip-list {
		.el-tabs__header {
			background-color: #fff;
			border-radius: 0 0 5px 5px;
			padding: 20px 20px 0 40px;
		}

		.el-tabs__nav-wrap::after {
			background-color: #fff;
		}

		.el-tabs__active-bar {
			height: 4px;
		}

		.vip-page {
			.vip-content {
				.left {
					max-width: 300px;
					min-width: 300px;
					background-color: #fff;
					margin-right: 10px;
					padding: 20px 10px;

					.category-tree-container {
						height: calc(100vh - 230px);
					}

					button {
						margin: 10px 10px 0 0;
					}

					.pointerEvents {
						pointer-events: none;
						opacity: 0.5;
					}
				}

				.right {
					background-color: #fff;
					padding: 20px 10px;
					overflow: hidden;

					.scrollbar-container {
						height: calc(100vh - 230px);
					}

					.list-table {
						padding: 0 10px;

						.vip-member {
							display: flex;

							.vip-avatar {
								overflow: hidden;
								flex: 0 0 68px;
								height: 68px;
								border: 1px solid #e7e7e7;
								border-radius: 20%;
								margin: 10px 10px 10px 0;
								background-color: #cccccc;
							}

							.vip-name {
								font-size: 14px;
								font-style: normal;
								font-weight: 700;
								line-height: 18px;

								.v-user-sex {
									font-size: 18px;
								}
							}

							.vip-detail {
								font-family: '苹方 中等', '苹方', sans-serif;
								font-weight: 400;
								font-style: normal;
								line-height: 22px;
							}
						}
					}
				}
			}
		}
	}
</style>
